import React, { useState } from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import axios from 'axios';

interface LoginProps {
  onLogin: (token: string) => void;
}

const Login: React.FC<LoginProps> = ({ onLogin }) => {
  const [loading, setLoading] = useState(false);

  const onFinish = async (values: { username: string; password: string }) => {
    setLoading(true);
    try {
      console.log('正在尝试登录...');
      const response = await axios.post('/api/login', values, {
        headers: {
          'Content-Type': 'application/json',
        },
      });
      console.log('登录响应:', response);
      if (response.data && response.data.token) {
        onLogin(response.data.token);
        message.success('登录成功');
      } else {
        message.error('登录失败：返回数据格式不正确');
      }
    } catch (error: any) {
      console.error('登录错误:', error);
      if (error.response) {
        console.error('错误响应:', error.response.data);
        message.error(`登录失败: ${error.response.data.error || '用户名或密码错误'}`);
      } else if (error.request) {
        console.error('请求错误:', error.request);
        message.error('无法连接到服务器，请检查网络连接');
      } else {
        console.error('错误:', error.message);
        message.error(`登录失败: ${error.message}`);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: 400, margin: '100px auto' }}>
      <Card title="登录" bordered={false}>
        <Form
          name="login"
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              size="large"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} block size="large">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login; 